package com.idefav.crossdomaintest.controllers;

import com.idefav.crossdomaintest.config.CommonConfig;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

@Controller
public class Hello2Controller {

    @Resource
    private CommonConfig commonConfig;

    @RequestMapping(value = "/taobao",method = RequestMethod.GET)
    public String index(HttpServletResponse response,@RequestParam(name = "u",defaultValue = "idefav") String userName){
        Cookie cookie=new Cookie("tb_nk",userName);
        cookie.setDomain("taobao.com");
        response.addCookie(cookie);
        return "hello2/index";
    }

    @RequestMapping(value = "login_api",method = RequestMethod.GET)
    @ResponseBody
    public String getCookie(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
        Cookie[] cookies = request.getCookies();
        StringBuilder stringBuilder=new StringBuilder();
        for (Cookie cookie : cookies) {
            String cookieName=cookie.getName();
            String cookieVal= URLDecoder.decode(cookie.getValue(),"utf-8");
            stringBuilder.append("document.cookie='"+cookieName+"='+"+" escape('"+cookieVal+"') "+"+';path=/';");
        }
        return stringBuilder.toString();
    }

    @RequestMapping(value = "/tmall",method = RequestMethod.GET)
    public String invoke(Model model){

        model.addAttribute("login_api",commonConfig.getLogin_api());
        return "/hello2/invoke";
    }
}
